package com.znsd.zl.order.controller;

import com.znsd.zl.order.dao.IOrderDao;
import com.znsd.zl.order.entity.OrderEntity;
import com.znsd.zl.order.entity.vo.HouseRentVo;
import com.znsd.zl.order.entity.vo.OrderEntityVo;
import com.znsd.zl.order.entity.vo.UserOrderVo;
import com.znsd.zl.order.service.IOrderService;
import com.znsd.zl.order.service.impl.DelayedService;
import com.znsd.zl.order.utils.RedisUtils;
import com.znsd.zl.utils.BaseController;
import com.znsd.zl.utils.PageUtils;
import com.znsd.zl.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * @ClassName OrderController
 * @Description 订单服务控制器接口
 * @author jaypdd
 * @email jaypdd@163.com
 * @date 2020-08-16 21:16:34
 * @Version v1.0
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController extends BaseController<IOrderService, OrderEntity, Integer> {

	@Autowired
	DelayedService delayedService;
	@Autowired
	RedisUtils redisUtils;
	@Resource
	IOrderDao orderDao;

	/**
	 * 分页查询订单
	 * @param params
	 * @param pageNum  当前请求页码
	 * @param pageSize 请求的记录数
	 * @return
	 */
	@Override
	@GetMapping("/{pageNum}/{pageSize}")
	public R pageFind(@RequestParam Map<String, Object> params,
	                  @PathVariable(name = "pageNum") Integer pageNum,
	                  @PathVariable(name = "pageSize") Integer pageSize) {
		PageUtils pageUtils = null;
		try{
			pageUtils = service.findAllOrder(pageNum, pageSize, params);

		}catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器异常，请稍后重试");
		}
		log.info("分页查询，pageNum===>{}，pageSize===>{}，pageUtils===>{}", pageNum, pageSize, pageUtils.toString());

		return R.ok().put("page", pageUtils);
	}
	
	/**
	 * 查询订单
	 * @return
	 */
	@GetMapping("/query/{id}/{userId}")
	public R pageFindQuery(@PathVariable("id") Integer id,@PathVariable("userId") Integer userId) {
		PageUtils pageUtils = null;
		try{
			OrderEntity on=new OrderEntity();
			on.setId(id);
			on.setUserId(userId);
			pageUtils= service.findAllTradeOrder(on);
		}catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器异常，请稍后重试");
		}
		return R.ok().put("page", pageUtils) ;
	}
	
	
	
	
	/**
	 * 添加订单
	 * @param orderEntity 需要 用户Id 实际支付金额 房源负责人Id 租房信息Id 支付方式 等字段
	 * @return
	 */
	@Override
	@PostMapping
	public R save(@RequestBody OrderEntity  orderEntity) {
		//订单创建日期
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm");
		try {
			Long orderNo=Long.decode(getUUID());
			orderEntity.setOrderNo(orderNo);
			orderEntity.setCreateTime(dateFormat.format(new Date()));
			log.info("添加信息data===>{}", orderEntity);
			return service.saveOrder(orderEntity) ? R.ok() : R.error("添加失败");
		}catch (Exception e){
			e.printStackTrace();
			return R.error();
		}
	}


	/**
	 * 逻辑删除
	 * @param ids 删除的id集合
	 * @return
	 */
	@Override
	@DeleteMapping
	public R deleteBatch(@RequestBody List<Integer> ids) {
		try {
			log.info("批量删除的ids===>{}", ids);
			service.setIsDelete(ids);
		}catch (Exception e){
			e.printStackTrace();
			return R.error("服务器异常，请稍后重试");
		}
		return R.ok();
	}


	/**
	 * 随机获取12为的数字
	 * @return
	 */
	public  String getUUID(){
		//随机生成一位整数
		int random = (int) (Math.random()*9+1);
		String valueOf = String.valueOf(random);
		//生成uuid的hashCode值
		int hashCode = UUID.randomUUID().toString().hashCode();
		//可能为负数
		if(hashCode<0){
			hashCode = -hashCode;
		}
		String value = valueOf + String.format("%012d", hashCode);
		System.out.println(value);
		return value;
	}


	/**
	 * 查看用户的租赁
	 * @param userId
	 * @return
	 */
	@RequestMapping("houseRent/{userId}")
	public R findHouseRent(@PathVariable(name="userId") Integer userId){

		List<HouseRentVo> houseRent = service.findHouseRent(userId);

		return R.ok().put("list",houseRent);

	}


	/**
	 * 根据订单获取租房记录
	 * @param rentId
	 * @return
	 */
	@RequestMapping("orderRent/{page}/{limit}/{rentId}")
	public R orderRent(@PathVariable("page") Integer page ,@PathVariable("limit")Integer limit ,@PathVariable("rentId") Integer rentId){

		List<UserOrderVo> userOrderVos = service.orderRent(rentId,page,limit);

		return R.ok().put("list",userOrderVos);
	}


	/**
	 * 模拟下单
	 * @param orderEntity  保存数据
	 * @param status       微信是否支付成功
	 * @return
	 */
	@GetMapping("/placeAnOrder")
	public R placeAnOrder(  OrderEntityVo orderEntity,  Boolean status) {
		String msg = this.service.placeAnOrder(orderEntity, status);
		return R.ok().put("msg",msg);
	}

	/**
	 *  取消或者付款
	 * @param orderId   订单编号
	 * @param status   1 状态付款   3 状态取消图库
	 * @return
	 */
	@PostMapping("/cancelOrder")
	public R cancelAndPayment(Integer orderId,Integer status) {
		// 防止延迟队列中不存在orderId
		if (delayedService.checkOrderId(orderId)) {
			delayedService.update(orderId,status);
		}
		String msg = null;
		if (status == 1){
			log.error("取消在付款延迟队列消息丢失，请手动补充，orderId===》{}", orderId);
			this.service.setStatusSuccess(orderId);
			msg = "支付成功";
		} else {
			this.service.setStatusCancel(orderId);
			msg = "取消成功";
		}

		return R.ok().put("msg",msg);
	}

	@GetMapping("/set")
	public Boolean set(String key) {
		return redisUtils.set(key);
	}

	@GetMapping("/get")
	public String get(String key) {
		return redisUtils.get(key);
	}

	@GetMapping("/del")
	public Long del(String key) {
		return redisUtils.del(key);
	}

	@GetMapping("/rentCount")
	public Integer queryRentCount(Integer rentId){
		return orderDao.queryOrderRentAmount(rentId);
	}

}
